const Axios = require("axios")
const X2JS = require('x2js');

const pay = require('./pay');
const logger = require('../utils/logger');
const config = require('../config/config.json');
const { randomString } = require('../utils/help');

const wxPayAddress = process.env.WX_PAY_ADDRESS;
const wxPayAppId = process.env.WX_PAY_APP_ID;
const wxPayMchId = process.env.WX_PAY_MERCHANT_ID;
const wxPaySubMchId = process.env.WX_PAY_SUB_MERCHANT_ID;
const wxPayKey = process.env.WX_PAY_MERCHANT_KEY;

function wxPaySign(params) {
  return pay.sign(params, wxPayKey);
}

function getWxPaySignedXml(params) {
  return pay.getSignedXml(params, wxPayKey);
}


const wxPay = async (billno, amount, notifyUrl) => {
  // 生成随机字符串
  const nonce_str = randomString(32)

  let chargeCNY = Math.ceil(amount * 100) // 金额(分)转换为元 amount * 100

  const opts = {
    appid: wxPayAppId, // 公众账号ID
    body: "Account Creation", // 商品描述
    mch_id: wxPayMchId,  // 商户号
    sub_mch_id: wxPaySubMchId,  // 子商户号
    nonce_str: nonce_str, // 随机字符串
    notify_url: notifyUrl, // 接收通知消息的地址
    out_trade_no: billno, // 订单号
    trade_type: "NATIVE", // 支付类型(扫码支付)
    fee_type: "CNY",  // 币种
    total_fee: chargeCNY
  }

  let xmlData = getWxPaySignedXml(opts);
  logger.info("=====wxPay-xmlData", xmlData);

  const ret = await Axios({
    method: 'post',
    url: wxPayAddress,
    data: xmlData
  })

  const x2js = new X2JS();
  const data = x2js.xml2js(ret.data.replace(/<xml>|<\/xml>/g, ""))

  if (data.return_code === 'SUCCESS') {
    return {
      retcode: 0,
      openUrl: `${config[process.env.NODE_ENV].serviceUrl}/pay/wxpay?code_url=${encodeURIComponent(data.code_url)}&total_fee=${opts.total_fee}`,
      retmsg: 'success'
    }
  } else {
    return {
      retcode: 400,
      retmsg: data.return_msg
    }
  }
}

module.exports = {
  wxPay: wxPay,
  wxPaySign: wxPaySign,
  getWxPaySignedXml: getWxPaySignedXml
}